﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace Lists
{
    static public class IPList
    {
        public struct IPUser
        {
            public string username;
            public string ip;
            public IPUser(string username, string ip)
            {
                this.username = username;
                this.ip = ip;
            }
        }

        static public List<IPUser> ipList { get; set; }

        static IPList()
        {
           ipList = new List<IPUser>();
        }

        static public void AddIPUser(string username, string ip)
        {
            for (int i = 0; i < ipList.Count; i++)
            {
                if (username == ipList[i].username)
                    return;
            }
            ipList.Add(new IPUser(username, ip));
        }

        static public void RemoveIPUser(string username)
        {
            for (int i = 0; i < ipList.Count; i++)
            {
                if (username == ipList[i].username)
                {
                    ipList.RemoveAt(i);
                    return;
                }
            }
        }

        static public string findUsersIP(string username)
        {
            for (int i = 0; i < ipList.Count; i++)
            {
                if (username == ipList[i].username)
                {
                    return ipList[i].ip;
                }
            }
            return null;
        }

        static public string GetPublicIP()
        {
            String direction = "";
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader stream = new StreamReader(response.GetResponseStream()))
            {
                direction = stream.ReadToEnd();
            }

            //Search for the ip in the html
            int first = direction.IndexOf("Address: ") + 9;
            int last = direction.LastIndexOf("</body>");
            direction = direction.Substring(first, last - first);

            return direction;
        }
    }
}
